//
//  LCMessageViewController.m
//  EnterpriseCloud
//
//  Created by 东亨 on 2017/7/11.
//  Copyright © 2017年 lichao. All rights reserved.
//

#import "LCMessageViewController.h"
#import "LCVoiceTableViewCell.h"
#import "LCVideoTableViewCell.h"
#import "LCBaoTableViewCell.h"
#import "LCMoreTableViewCell.h"
#import "LCMoveViewController.h"
#import "MessageModel.h"
#import "LLImagePickerModel.h"
#import "CountHeight.h"
static NSString *cellIdentifier = @"LCVoiceTableViewCell";//不带视屏、图片
static NSString *cellIdentifier1 = @"LCVideoTableViewCell";//带视频、图片
static NSString *cellIdentifier2 = @"LCBaoTableViewCell";
static NSString *cellIdentifier3 = @"LCMoreTableViewCell";
@interface LCMessageViewController ()<UITableViewDelegate,UITableViewDataSource,LCBaoTableViewCellDataSource,LCVideoTableViewCellDataSource,LCVideoTableViewCellDelegate,LCVoiceTableViewCellDelegate,AVAudioPlayerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong,nonatomic)NSMutableDictionary *dataDic;
@property (strong,nonatomic)NSMutableArray      *dataArray;
@property (copy,nonatomic)NSString  *file_function;//区别是留言建议还是保修
@property (strong,nonatomic)AVPlayer  *player;
@end
static NSMutableDictionary *_musices;
@implementation LCMessageViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBarTitle:_typeStr];
    _dataDic = [[NSMutableDictionary alloc]initWithCapacity:0];
    _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    [self loadCustomeView];
}
- (void)loadCustomeView
{
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    [_tableView registerNib:[UINib nibWithNibName:@"LCVoiceTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
    [_tableView registerNib:[UINib nibWithNibName:@"LCVideoTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier1];
    [_tableView registerNib:[UINib nibWithNibName:@"LCBaoTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier2];
    [_tableView registerNib:[UINib nibWithNibName:@"LCMoreTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier3];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{//下拉刷新
        [self loadData];
    }];
    [_tableView.mj_header beginRefreshing];
}
-(void)loadData
{
    [_dataArray removeAllObjects];
    [_dataDic setObject:@"2" forKey:@"pageSize"];
    [_dataDic setObject:@"1" forKey:@"pageNum"];
    if (get_sp(@"company_id"))
    {
        [_dataDic setObject:get_sp(@"company_id") forKey:@"company_id"];
    }
    [MDataProvider getMessageListBodyDic:_dataDic typeStr:[_typeStr isEqualToString:@"留言"]?0:1 sucess:^(NSArray *array) {
        [_dataArray addObjectsFromArray:array];
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        if (array.count<10)
        {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }
        else
        {
            self.tableView.mj_footer.state = MJRefreshStateIdle;
        }
        
    } faile:^(NSString *str) {
        [_tableView.mj_header endRefreshing];
        [SVProgressHUD showErrorWithStatus:str];
    }];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataArray.count)
    {
        //两行
        FileType type = [self fileTypeWithIndex:indexPath.row];
        if (type == All||type == VideoAndImg)
        {
            return 180;
        }
        else
        {
            return 95;
        }
    }
    else if(indexPath.row == _dataArray.count)
    {
        return 55;
    }
    else
    {
         return 539;
    }
}
#pragma mark -UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count+2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < _dataArray.count)
    {
        FileType type = [self fileTypeWithIndex:indexPath.row];
        MessageModel *model = [_dataArray objectAtIndex:indexPath.row];
        LCVideoTableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
        cell1.audioBtn.tag = indexPath.row;
        cell1.tag  = indexPath.row;
        cell1.delegate = self;
        cell1.dataSource = self;
        cell1.numberLbl.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        cell1.titleLbl.text = model.message_content;
        cell1.timeLbl.text = model.message_time;
        
        LCVoiceTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell2.delegate = self;
        cell2.titleLbl.text = model.message_content;
        cell2.timeLbl.text = model.message_time;
        cell2.audioBtn.tag = indexPath.row;
        cell2.numberLbl.text = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        //根据文件类型判断文件格式
        if (type == All)
        {
            //全部包括视频或图片、音频
            return cell1;
        }
        else if(type == VideoAndImg)
        {
            //视频或图片
            cell1.audioBtn.hidden = YES;
            return cell1;
        }
        else if (type == Audio)
        {
            //音频
            return cell2;
        }
        else
        {
           //纯文字
            cell2.audioBtn.hidden = YES;
            return cell2;
        }
    }
    else if(indexPath.row == _dataArray.count)
    {
        LCMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier3];
        cell.separatorInset =UIEdgeInsetsMake(0,0, 0, SCREEN_WIDTH);
        cell.moveClickBlock = ^
        {
            LCMoveViewController *vc = [[LCMoveViewController alloc]init];
            vc.typeStr = _typeStr;
            [self.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }
    else
    {
        LCBaoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier2];
        if ([_typeStr isEqualToString:@"留言"])
        {
            cell.propertyImg.hidden = NO;
            cell.properLbl.hidden = NO;
            cell.properBtn.hidden = NO;
        }
        else
        {
            cell.propertyImg.hidden = YES;
            cell.properLbl.hidden = YES;
            cell.properBtn.hidden = YES;
        }
        cell.dataSource = self;
        cell.separatorInset =UIEdgeInsetsMake(0,0, 0, SCREEN_WIDTH);
        return cell;
    }
}
#pragma mark -LCBaoTableViewCellDataSource
- (NSString *)chooseTypeBtnClick
{
    if ([_typeStr isEqualToString:@"留言"])
    {
        self.file_function = @"message";
    }
    else
    {
        self.file_function = @"repair";
    }
    return _file_function;
}
#pragma mark -LCVideoTableViewCellDelegate
- (void)videoChooseAudioWithIndex:(NSInteger)index
{
    MessageModel *model = [_dataArray objectAtIndex:index];
    for (FileListModel *fileModel in model.fileList)
    {
        if ([fileModel.file_type isEqualToString:@".mp3"])
        {
            //语音
            NSString *mediaUrl = [NSString stringWithFormat:@"%@/%@%@",ENCLOUD_URL,fileModel.file_path,fileModel.file_name];
            [self playMusicWithUrl:[NSURL URLWithString:mediaUrl]];
        }
    }
}
#pragma mark -LCVideoTableViewCellDataSource
-(NSMutableArray *)loadDataWithLCVideoWithCell:(LCVideoTableViewCell *)voiceCell
{
      NSMutableArray *llModelArr = [[NSMutableArray alloc]initWithCapacity:0];
      MessageModel *model = [_dataArray objectAtIndex:voiceCell.tag];
      for (FileListModel *fileModel in model.fileList)
      {
          if (![fileModel.file_type isEqualToString:@".mp3"])
          {
              LLImagePickerModel *model = [[LLImagePickerModel alloc]init];
              //不是mp3格式
              if ([fileModel.file_type isEqualToString:@".mp4"]||[fileModel.file_type isEqualToString:@".mov"]||[fileModel.file_type isEqualToString:@".3gp"])
              {
                  NSString *mediaUrl = [NSString stringWithFormat:@"%@/%@%@",ENCLOUD_URL,fileModel.file_path,fileModel.file_name];
                  model.mediaURL = [NSURL URLWithString:mediaUrl];
                  //取出视频第一帧图片
                  model.image  =img(@"video@2x");
                  model.isVideo = YES;
              }
              else
              {
                  NSString *imgUrl = [NSString stringWithFormat:@"%@/%@%@",ENCLOUD_URL,fileModel.file_path,fileModel.file_name];
                  model.imageUrlString = imgUrl;
              }
              [llModelArr addObject:model];
          }
      }
    return llModelArr;
}
#pragma mark -LCVoiceTableViewCellDelegate
- (void)audioChooseAudioWithIndex:(NSInteger)index
{
     MessageModel *model = [_dataArray objectAtIndex:index];
    for (FileListModel *fileModel in model.fileList)
    {
        if ([fileModel.file_type isEqualToString:@".mp3"])
        {
            //语音
            NSString *mediaUrl = [NSString stringWithFormat:@"%@/%@%@",ENCLOUD_URL,fileModel.file_path,fileModel.file_name];
            [self playMusicWithUrl:[NSURL URLWithString:mediaUrl]];
        }
    }
}
- (FileType)fileTypeWithIndex:(NSInteger)index
{
    MessageModel *model = [_dataArray objectAtIndex:index];
    NSMutableArray *fileTypeArr = [[NSMutableArray alloc]initWithCapacity:0];
    for (FileListModel *fileModel in model.fileList)
    {
        //文件类型
        [fileTypeArr addObject:fileModel.file_type];
    }
    //根据文件类型判断文件格式
    if ([fileTypeArr containsObject:@".png"]||[fileTypeArr containsObject:@".jpg"]||[fileTypeArr containsObject:@".mov"]||[fileTypeArr containsObject:@".mp4"]||[fileTypeArr containsObject:@".3gp"])
    {
        if ([fileTypeArr containsObject:@".mp3"])
        {
            return All;
        }
        else
        {
            return VideoAndImg;//图片或者视频
        }
    }
    else if([fileTypeArr containsObject:@".mp3"])
    {
        return Audio;
    }
    else
    {
        return Message; //纯文字
    }
}
/**
 *播放音乐文件
 */
- (void)playMusicWithUrl:(NSURL *)fileUrl
{
    [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    // AVPlayerItem是一个包装音乐资源的类，初始化时可以传入一个音乐的url
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:fileUrl];        //通过AVPlayerItem初始化player
    _player = [[AVPlayer alloc] initWithPlayerItem:item];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord
             withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker
                   error:nil];
    [self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{   //注意这里查看的是self.player.status属性
    if ([keyPath isEqualToString:@"status"])
    {
        switch (self.player.status)
        {
            case AVPlayerStatusUnknown:
            {
                NSLog(@"未知转态");
            }
                break;
            case AVPlayerStatusReadyToPlay:
            {
                [_player play];
            }
               break;
            case AVPlayerStatusFailed:
            {
                NSLog(@"加载失败");
            }
               break;
            default:
               break;
        }
    }
}
@end
